package com.ice.remoting.netty;

import com.ice.remoting.data.RemotingCommand;

import com.ice.remoting.exception.RemotingException;
import com.ice.remoting.exception.RemotingSendRequestException;
import com.ice.remoting.exception.RemotingTimeoutException;
import io.netty.channel.Channel;
import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Getter
@Setter
public class ResponseFuture {
    private final int opaque;
    private final RemotingCommand request;
    private final Channel channel;
    private InvokeCallback invokeCallback;
    private final long timeoutMillis;

    private final long beginTimestamp = System.currentTimeMillis();

    private volatile boolean sendRequestOK = true;
    private volatile RemotingCommand responseCommand;

    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    private final AtomicBoolean executeCallbackOnlyOnce = new AtomicBoolean(false);
    private volatile Throwable cause;

    public ResponseFuture(Channel channel, int opaque,long timeoutMillis, InvokeCallback invokeCallback) {
        this(channel, opaque, null,timeoutMillis, invokeCallback);
    }

    public ResponseFuture(Channel channel, int opaque, RemotingCommand request,long timeoutMillis, InvokeCallback invokeCallback) {
        this.channel = channel;
        this.opaque = opaque;
        this.request = request;
        this.timeoutMillis = timeoutMillis;
        this.invokeCallback = invokeCallback;
    }


    public void putResponse(final RemotingCommand responseCommand) {
        this.responseCommand = responseCommand;
        this.countDownLatch.countDown();
    }

    public void executeInvokeCallback() {
        if (invokeCallback != null) {
            // 多次传递导致并发的情况
            if (this.executeCallbackOnlyOnce.compareAndSet(false, true)) {
                RemotingCommand response = getResponseCommand();
                if (response != null) {
                    invokeCallback.operationSucceed(response);
                } else {
                    if (!isSendRequestOK()) {
                        invokeCallback.operationFail(new RemotingSendRequestException(channel.remoteAddress().toString(), getCause()));
                    } else if (isTimeout()) {
                        invokeCallback.operationFail(new RemotingTimeoutException(channel.remoteAddress().toString(), getTimeoutMillis(), getCause()));
                    } else {
                        invokeCallback.operationFail(new RemotingException(getRequest().toString(), getCause()));
                    }
                }
                invokeCallback.operationComplete(this);
            }
        }
    }

    public boolean isTimeout() {
        long diff = System.currentTimeMillis() - this.beginTimestamp;
        return diff > this.timeoutMillis;
    }
}
